<template>
  <div class="account-box">
    <div class="toggle">
      <a href="javascript:;" @click="activeName='account'" v-if="activeName==='note'">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a href="javascript:;" @click="activeName='note'" v-if="activeName==='account'">
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <Form ref="formCom" class="form" v-slot="{errors}" :validation-schema="veeValidateSchema">
        <!-- 账号登录 -->
      <template v-if="activeName==='account'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field  :class="{ error: errors.account }" type="text" v-model="form.account" name='account' placeholder="请输入用户名或手机号" />
          </div>
          <div class="error" v-if="errors.account"><i class="iconfont icon-warning" />{{errors.account}}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field  :class="{ error: errors.password }" type="password" v-model="form.password" name='password' placeholder="请输入密码" />
          </div>
          <div class="error" v-if="errors.password"><i class="iconfont icon-warning" />{{errors.password}}</div>
        </div>
      </template>
      <!-- 邮箱手机短信登录 -->
      <template  v-if="activeName==='note'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field  :class="{ error: errors.mobile }" type="text" name='mobile' v-model="form.mobile" placeholder="请输入手机号" />
          </div>
          <div class="error" v-if="errors.mobile"><i class="iconfont icon-warning" />{{errors.mobile}}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field  :class="{ error: errors.code }" type="text" name='code' placeholder="请输入验证码" v-model="form.code" />
            <span class="code" @click="send">{{number===0?'发送验证码':`${number}秒后发送`}}</span>
          </div>
          <div class="error" v-if="errors.code"><i class="iconfont icon-warning" />{{errors.code}}</div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
            <!-- as会渲染标签 -->
             <!-- 💥 Field 可以通过 as 属性指定渲染成其他标签或者自定义组件，as 默认值为 input -->
            <Field as='XtxCheckbox' :class="{ error: errors.isAgree }"  name='isAgree' v-model="form.isAgree"></Field>
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="errors.isAgree"><i class="iconfont icon-warning" />{{errors.isAgree}}</div>
      </div>
      <a href="javascript:;" class="btn" @click="loginBtn">登录</a>
    </Form>
    <div class="action">
      <a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
         <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
      </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<script>
import veeValidateSchema from '@/utils/vee-validate-schema'
import { Form, Field } from 'vee-validate'
import { ref, reactive } from 'vue'
import { userAccountLogin, userMobileLoginMsg, userMobileLogin } from '@/api/user'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import Message from '@/components/library/Message'
// import { useIntervalFn } from '@vueuse/core'
import { useTimer } from '@/hooks'
export default {
  name: 'LoginForm',
  components: {
    Form, Field
  },
  setup () {
    const activeName = ref('account')
    const store = useStore()
    const router = useRouter()
    // const route = useRoute()
    // 表单对象数据
    const form = reactive({
      isAgree: true,
      account: 'xiaotuxian001',
      password: 123456,
      mobile: 13012345699,
      code: null
    })

    // const formCom = ref(null)
    // 登录逻辑
    const loginBtn = async () => {
    //   console.log(formCom)
    // 表单的校验
      const valid = await formCom.value.validate()
      if (!valid) return Message({ type: 'error', message: '表单校验失败' })

      // 验证通过
      try {
        let res
        if (activeName.value === 'account') {
          // 情况1：账号密码登录
          res = await userAccountLogin(form)
          // console.log(result)
        } else {
          // 手机号登录
          res = await userMobileLogin(form)
        }
        // 存储到vuex
        store.commit('user/setUser', res.result)
        // 2. 页面跳转（两种情况：1.回跳到某个页面 2.跳转首页）
        // 第一种
        // const redirectUrl = route.query.redirectUrl
        // 第二种router.currentRoute.value 获取当前路由
        const redirectUrl = router.currentRoute.value.query.redirectUrl
        // console.log(redirectUrl)
        //   跳转
        router.push(redirectUrl || '/')
        Message({ type: 'success', message: '登录成功' })
        // 登录成功后合并购物车数据
        store.dispatch('cart/mergeLocalCart')
      } catch (error) {
        console.dir(error)
        // alert(error.response.data.message)
        Message({ type: 'error', message: error.response.data.message })
      }
    }
    const { number, formCom, send } = useTimer(() => userMobileLoginMsg(form.mobile), form)
    // const number = ref(0)
    // resume 用于启动定时器的函数
    // pause  用于暂停定时器的函数
    // const { resume, pause } = useIntervalFn(() => {
    //   number.value--
    //   if (number.value <= 0) {
    //     pause()
    //   }
    // }, 1000, { immediate: false })

    // 发送验证码
    // const send = async () => {
    //   // 校验单个
    //   const valid = veeValidateSchema.mobile(form.mobile)
    //   // console.log(valid)
    //   if (valid === true) {
    //     if (number.value !== 0) return
    //     number.value = 60
    //     resume()
    //     try {
    //       // 发送验证码
    //       const res = await userMobileLoginMsg(form.mobile)
    //       console.log(res)
    //       Message({ type: 'success', message: '验证码发送成功' })
    //     } catch (error) {
    //       console.log(error)
    //       Message({ type: 'error', message: error.response.data.message || '验证码已发送，稍后再试' })
    //     }
    //   } else {
    //     // console.log(formCom)
    //     formCom.value.setFieldError('mobile', valid)
    //   }
    // }

    return { activeName, veeValidateSchema, form, formCom, loginBtn, send, number }
  }
}
</script>

<style lang="less" scoped>
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,&:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
